﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
using System.Security.Principal;
using System.Threading;
using System.Management;
using System.Management.Instrumentation;
using System.Net.NetworkInformation;
using System.Collections;
//using NativeWifi;

namespace FRCNetworkTool
{
    public partial class Form1 : Form
    {
        #region Global Variables
        //File Settings

        string pwd = "";//"C:\\Dropbox\\FRC-1208\\Projects\\frc-network-tool\\FRCNetworkTool";
        string configfile = "";
        //Host Computer
        string hostipaddr;
        string hostsubnet;
        string hostgateway;
        bool changeactivenic = true;
        List<NIC> myNICS = new List<NIC>();
      
        NetworkInterface[] interfaces; 
        
        //FRC Network
        List<Team> myTeams = new List<Team>();
        List<Device> myDevices = new List<Device>();
        List<Network> myNetworks = new List<Network>();
        #endregion
        public Form1()
        {
            try
            {
                InitializeComponent();
                tabcontrol.SelectedTab = this.tab_Configure;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        #region ManualTab
        private void Change_Network_Click(object sender, EventArgs e)
        {
            bool validstring = false;
            string NIC = lb_NIC.SelectedItem.ToString();
            if (manual_ch_dhcp.Checked == false)
            {
                validstring = ValidateString(manual_t_ip.Text) && ValidateString(manual_t_subnet.Text) && ValidateString(manual_t_gateway.Text);
                if (validstring)
                {
                    this.Cursor = Cursors.WaitCursor;
                    ChangeNetworkSettings_STATIC(NIC, manual_t_ip.Text, manual_t_subnet.Text, manual_t_gateway.Text);
                    UpdateCurrentIPSettings();
                    this.Cursor = Cursors.Default;
                }
                else
                {
                    t_Results.Text = "Invalid IP Settings";
                }
                //UpdateNIC(lb_NIC.SelectedItem.ToString(), false, manual_hostip.Text, manual_hostsubnet.Text, manual_hostgateway.Text);
            }
            else
            {
                this.Cursor = Cursors.WaitCursor;
                ChangeNetworkSettings_DHCP(NIC);
                UpdateCurrentIPSettings();
                this.Cursor = Cursors.Default;
                //UpdateNIC(lb_NIC.SelectedItem.ToString(), true, null,null,null);
            }
        }
        private void manual_c_DHCP_Click(object sender, EventArgs e)
        {
            if (manual_ch_dhcp.Enabled == true)
            {
                manual_t_ip.Enabled = false;
                manual_t_subnet.Enabled = false;
                manual_t_gateway.Enabled = false;
            }
            else
            {
                manual_t_ip.Enabled = true;
                manual_t_subnet.Enabled = true;
                manual_t_gateway.Enabled = true;
            }
        }
        private void manual_b_pinggateway_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 4; i++)
            {
                t_Results.AppendText(string.Format("Pinging Device:  {0}", manual_t_gateway.Text));
                t_Results.AppendText(string.Format("   Time To Live:{0}\r\n", pingdevice(manual_t_gateway.Text)));
            }
        }
        #endregion
        #region Global Functions
        public void readsettings()
        {
            //TcpIPWMI mytcp = new TcpIPWMI();
            string tempstr = "";
            //string[] settings = mytcp.ListIP(tempstr);
            //manual_cb_NIC.
            string tempstr1;
            string tempstr2;
            string[] tempstrarray;
            myTeams.Clear();
            myDevices.Clear();
            myNICS.Clear();
            myNetworks.Clear();
            try
            {
                lb_NIC.Items.Clear();
                /*interfaces = NetworkInterface.GetAllNetworkInterfaces();
                int i = 0;
                foreach (NetworkInterface interfaceobject in interfaces)
                {
                    NIC mynic = new NIC();
                    if ((interfaceobject.Name == "Local Area Connection") || (interfaceobject.Name == "Wireless Network Connection"))
                    {
                        mynic.NICName = interfaceobject.Name;
                        mynic.status = false;
                        mynic.wireless = false;
                        mynic.interfaceindex = i;
                        myNICS.Add(mynic);
                    }
                    i++;
                   
                    
                }*/
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * From Win32_NetworkAdapter Where PhysicalAdapter=True");
                foreach (ManagementObject obj in searcher.Get())
                {
                    NIC mynic = new NIC();
                    mynic.WMINICName = obj["ProductName"].ToString();
                    //mynic.status = obj["Status"].ToString();
                    mynic.interfaceindex = Convert.ToInt32(obj["Index"].ToString());
                    mynic.commonName = obj["NetConnectionID"].ToString();
                    if (mynic.commonName.Contains("Wireless"))
                    {
                        mynic.wireless = true;
                    }
                    else
                    {
                        mynic.wireless = false;
                    }
                    if (string.Equals(mynic.commonName, "Local Area Connection"))
                    {
                        mynic.defaultlan = true;
                    }
                    else if (string.Equals(mynic.commonName, "Wireless Network Connection"))
                    {
                        mynic.defaultwlan = true;
                    }
                    else
                    {
                        mynic.defaultlan = false;
                        mynic.defaultwlan = false;
                    }
                    myNICS.Add(mynic);

                }
                
                string[] lines = System.IO.File.ReadAllLines(configfile);
                foreach (string line in lines)
                {

                    if (line.Contains("Team:"))
                    {
                        Team myTeam = new Team();
                        tempstr1 = line.Substring(line.IndexOf("Team:") + 6);
                        myTeam.TeamNumber = tempstr1.Replace(",", "");

                        tempstr2 = tempstr1.Substring(tempstr1.IndexOf(",") + 1);
                        tempstr1 = tempstr1.Substring(0, tempstr1.IndexOf(","));

                        tempstr1 = Convert.ToInt32(tempstr1).ToString();
                        tempstr2 = Convert.ToInt32(tempstr2).ToString();
                        myTeam.TeamNetwork = string.Format("{0}.{1}", tempstr1, tempstr2);
                        myTeams.Add(myTeam);
                    }
        
                    else if (line.Contains("Network:"))
                    {
                        Network myNetwork = new Network();
                        tempstr1 = line.Substring(line.IndexOf("Network:") + 9);
                        tempstrarray = tempstr1.Split(',');
                        myNetwork.NetworkName = tempstrarray[0];
                        tempstr2 = tempstrarray[1];
                        if (tempstr2.ToLower().Contains("internet"))
                        {
                            myNetwork.internet = true;
                            tempstr = tempstr2.Substring(tempstr2.IndexOf("Internet")+8);
                            myNetwork.order = Convert.ToInt32(tempstr);
                            myNetworks.Add(myNetwork);
                        }
                        else if (tempstr2.ToLower().Contains("robot"))
                        {
                            myNetwork.robot = true;
                            tempstr = tempstr2.Substring(tempstr2.IndexOf("Robot")+5);
                            myNetwork.order = Convert.ToInt32(tempstr);
                            myNetworks.Add(myNetwork);
                            
                        }

                    }
                    else if (line.Contains("Camera2011:"))
                    {
                        Device newdevice = new Device();
                        tempstr1 = line.Substring(0, line.IndexOf(":"));
                        tempstr2 = line.Substring(line.IndexOf(":") + 2);
                        newdevice.DeviceName = tempstr1;
                        newdevice.DeviceIP = tempstr2;
                        newdevice.excludeteamchange = true;
                        myDevices.Add(newdevice);
                    }
                    else if (line.Contains("RadioFactory:"))
                    {
                        Device newdevice = new Device();
                        tempstr1 = line.Substring(0, line.IndexOf(":"));
                        tempstr2 = line.Substring(line.IndexOf(":") + 2);
                        newdevice.DeviceName = tempstr1;
                        newdevice.DeviceIP = tempstr2;
                        newdevice.excludeteamchange = true;
                        myDevices.Add(newdevice);
                    }
                    else
                    {
                        Device newdevice = new Device();
                        tempstr1 = line.Substring(0, line.IndexOf(':'));
                        tempstr2 = line.Substring(line.IndexOf(':') + 2);
                        tempstr2 = "10." + myTeams[0] + "." + tempstr2;
                        tempstr2 = tempstr2.Replace(" ", "");
                        newdevice.DeviceName = tempstr1;
                        newdevice.DeviceIP = tempstr2;
                        myDevices.Add(newdevice);
                    }

                }
                cb_Devices.Items.Clear();
                foreach (Device mydevice in myDevices)
                {
                    cb_Devices.Items.Add(mydevice.DeviceName);
                }
                lb_Teams.Items.Clear();
                foreach (Team myTeam in myTeams)
                {
                    lb_Teams.Items.Add(myTeam.TeamNumber);
                }
                lb_NIC.Items.Clear();
                foreach (NIC mynic in myNICS)
                {
                    lb_NIC.Items.Add(mynic.commonName);
                }
                cb_Networks.Items.Clear();
                foreach (Network myNetwork in myNetworks)
                {
                    cb_Networks.Items.Add(myNetwork.NetworkName);
                }
                t_Results.Clear();

            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText("There was an error in the Settings File.\r\n");
                t_Results.AppendText(ex.Message);
                
            }

        }
        public void readipsettings()
        {

        }

        public bool ChangeNetworkSettings_STATIC(string NIC, string ip, string subnet, string gateway)
        {
            hostipaddr = ip;
            hostsubnet = subnet;
            hostgateway = gateway;
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "netsh.exe";
                string configtext = "interface ip set address name=\"" + NIC + "\" static " + ip + " " + subnet + " " + gateway;
                //string configtext = "interface ip set address name=\"Local Area Connection\" static 10.0.0.10 255.255.255.0 10.0.0.1 1";
                p.StartInfo.Verb = "runas";
                p.StartInfo.Arguments = configtext;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                p.WaitForExit(5000);
                t_Results.Text = p.StandardOutput.ReadToEnd();
                return true;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return false;
            }
        }
        public bool ChangeNetworkSettings_DHCP(string NIC)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "netsh.exe";
                string configtext = "interface ip set address name=\"" + NIC + "\" source=dhcp";
                //string configtext = "interface ip set address name=\"Local Area Connection\" static 10.0.0.10 255.255.255.0 10.0.0.1 1";
                p.StartInfo.Verb = "runas";
                p.StartInfo.Arguments = configtext;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                p.WaitForExit(5000);
                t_Results.Text = p.StandardOutput.ReadToEnd();
                return true;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return false;
            }
        }
        public int pingdevice(string ip)
        {
            try
            {
                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                options.DontFragment = true;
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;
                PingReply reply = pingSender.Send(ip, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                }
                return reply.Options.Ttl;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return -1;
            }
        }
        public int UpdateNIC(string NICName, bool enabledstate)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * From Win32_NetworkAdapter Where PhysicalAdapter=True");
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["ProductName"].ToString() == NICName)
                    {
                        if (enabledstate)
                        {
                            return Convert.ToInt32(obj.InvokeMethod("Enable", null));
                        }
                        else
                        {
                            return Convert.ToInt32(obj.InvokeMethod("Disable", null));
                        }
                    }
                }
                return -1;  //Should not Get here, hopefully
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return -1;
            }
        }

        public int UpdateCurrentIPSettings()
        {
            string[] tempstrarray = new string[1];
            try
            {
                ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection objMOC = objMC.GetInstances();
                foreach (ManagementObject obj in objMOC)
                {
                    if ((bool)obj["IPEnabled"])
                    {
                        cur_DHCP.Checked = (bool)obj["DHCPEnabled"];
                        tempstrarray = (string[])obj["IPAddress"];
                        cur_IP.Text = tempstrarray[0];
                        tempstrarray = (string[])obj["IPSubnet"];
                        cur_Subnet.Text = tempstrarray[0];
                        tempstrarray = (string[])obj["DefaultIPGateway"];
                        cur_Gateway.Text = tempstrarray[0];

                    }
                }
                return 0;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return -1;
            }
        }
        /*public int UpdateNIC(string NICName, bool dhcp, string ip, string subnet, string gateway)  //Not Used
        {

            int num = 0;
            try
            {
                if (dhcp)
                {
                    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection objMOC = objMC.GetInstances();
                    object objCurIP = null;
                    foreach (ManagementObject obj in objMOC)
                    {
                        objCurIP = obj.InvokeMethod("EnableDHCP", null);
     
                    }
                    return 0;
                }
                else
                {
                    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                    ManagementObjectCollection objMOC = objMC.GetInstances();
                    foreach (ManagementObject obj in objMOC)
                    {
                        if ((bool)obj["IPEnabled"])
                        {
                            ManagementBaseObject objIP = obj.GetMethodParameters("EnableStatic");
                            ManagementBaseObject objGate = obj.GetMethodParameters("SetGateways");
                            ManagementBaseObject objCurIP = null;
                            objIP["IPAddress"] = new string[] { ip };
                            objIP["SubnetMask"] = new string[] { subnet };
                            objGate["DefaultIPGateway"] = new string[] { gateway };
                            objGate["GatewayCostMetric"] = new int[] { 1 };

                            objCurIP = obj.InvokeMethod("EnableStatic", objIP, null);
                            objCurIP = obj.InvokeMethod("EnableStatic", objGate, null);
                            return num;
                        }
                    }
                    return 0;
                }
                
            }
            catch (Exception ex)
            {
                return -1;
            }
        }*/
        public bool ValidateString(string teststr)
        {
            string[] temparray;
            try
            {
                temparray = teststr.Split('.');
                for (int i = 0; i < temparray.Length; i++)
                {
                    if (Convert.ToInt32(temparray[i]) < 0)
                    {
                        return false;
                    }
                    else if (Convert.ToInt32(temparray[i]) > 255)
                    {
                        return false;
                    }
                }
                if (temparray.Length != 4)
                {
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return false;
            }
        }
        /*static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }*/
        /*public bool UpdateCurrentWifiAvailability()
        {
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                foreach (Wlan.WlanAvailableNetwork network in networks)
                {
                    t_Results.AppendText(GetStringForSSID(network.dot11Ssid));
                }
            }
            //Need to write code here
            try
            {
                foreach (Network myNetwork in myNetworks)
                {

                }
                return true;
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
                return false;
            }
        }
        */
        #endregion  
        #region VerifyTab

        private void verify_b_testall_Click(object sender, EventArgs e)
        {
            int result = -1;
            t_Results.Clear();
            foreach (Device mydevice in myDevices)
            {

                t_Results.AppendText(string.Format("Pinging Device: {0}({1})...", mydevice.DeviceName, mydevice.DeviceIP));
                result = pingdevice(mydevice.DeviceIP);
                if (result < 0)
                {
                    mydevice.status = false;
                    t_Results.AppendText("Unsuccessful\r\n");
                }
                else
                {
                    mydevice.status = true;
                    t_Results.AppendText(string.Format("{0}\r\n", result));
                }
            }
        }
        private void verify_b_ping_Click(object sender, EventArgs e)
        {
            t_Results.Clear();
            int num = -1;
            for (int i = 0; i < 4; i++)
            {
                t_Results.AppendText(string.Format("Pinging Device:  {0}...", verify_t_ip.Text));
                num = pingdevice(verify_t_ip.Text);
                if (num < 0)
                {
                    t_Results.AppendText("UnSuccessful\r\n");
                }
                else
                {
                    t_Results.AppendText(string.Format("Time To Live:{0}\r\n", num));
                }

            }
        }
        #endregion
        #region ConfigureTab
        private void configure_t_filepath_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                configfile = openFileDialog1.FileName;
                configure_t_filepath.Text = configfile;
            }
            configure_t_file.Clear();

            try
            {
                this.Cursor = Cursors.WaitCursor;


                string[] lines = System.IO.File.ReadAllLines(configfile);
                for (int i = 0; i < lines.Length; i++)
                {
                    configure_t_file.AppendText(lines[i]);
                    configure_t_file.AppendText("\r\n");
                }
                readsettings();
                lb_Teams.SetSelected(0, true);
                lb_NIC.SetSelected(0, true);
                UpdateCurrentIPSettings();
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                t_Results.Text = ex.Message;
            }
        }


        private void configure_b_CANCEL_Click(object sender, EventArgs e)
        {
            configure_t_file.Clear();
            try
            {
                string[] lines = System.IO.File.ReadAllLines(configfile);
                for (int i = 0; i < lines.Length; i++)
                {
                    configure_t_file.AppendText(lines[i]);
                    configure_t_file.AppendText("\r\n");
                }

            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
            }
        }

        private void configure_b_SAVE_Click(object sender, EventArgs e)
        {
            try
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(configfile))
                {
                    sw.Write(configure_t_file.Text);
                }
                readsettings();
            }
            catch (Exception ex)
            {
                t_Results.AppendText(ex.Message);
            }

        }
        #endregion
        #region Tasks
        private void b_REFRESH_Click(object sender, EventArgs e)
        {
            /*this.Cursor = Cursors.WaitCursor;
            //UpdateCurrentIPSettings();
            UpdateCurrentWifiAvailability();
            //Code to Update Wireless Network Availability
            this.Cursor = Cursors.Default;
            */


        }
        private void lb_NIC_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (changeactivenic)
            {
                this.Cursor = Cursors.WaitCursor;

                int errorcode = 0;
                int i = 0;
                bool done = false;
                while (!done)
                {
                    if (i >= myNICS.Count)
                    {
                        done = true;
                    }
                    else if ((lb_NIC.SelectedItem.ToString() == myNICS[i].commonName))
                    {
                        errorcode = UpdateNIC(myNICS[i].WMINICName, true);

                    }
                    else
                    {
                        errorcode = UpdateNIC(myNICS[i].WMINICName, false);

                    }
                    if (errorcode != 0)
                    {
                        t_Results.Clear();
                        t_Results.AppendText(string.Format("Error Updating {0} With Error Code: {1}.\r\n", lb_NIC.SelectedItem.ToString(), errorcode));
                        switch (errorcode)
                        {
                            case 5:
                                t_Results.AppendText(string.Format("Hint:  Are you Running as an Administrator?"));
                                break;
                            default:
                                break;
                        }


                        done = true;
                    }
                    else
                    {
                        t_Results.Clear();
                        UpdateCurrentIPSettings();
                    }
                    i++;
                }
                this.Cursor = Cursors.Default;
            }
        }
        private void lb_Teams_SelectedIndexChanged(object sender, EventArgs e)
        {
            string tempstr;
            foreach (Device mydevice in myDevices)
            {
                if (!mydevice.excludeteamchange)
                {
                    tempstr = mydevice.DeviceIP.Substring(mydevice.DeviceIP.LastIndexOf(".") + 1);
                    mydevice.DeviceIP = "10." + myTeams[lb_Teams.SelectedIndex].TeamNetwork + "." + tempstr;
                }
            }
        }
        private void task_imagecrio_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string tempstr = "";
                string NIC = lb_NIC.SelectedItem.ToString();
                foreach (NIC myNIC in myNICS)
                    foreach (Device mydevice in myDevices)
                    {
                        if (mydevice.DeviceName.ToLower().Contains("crio"))
                        {
                            hostgateway = mydevice.DeviceIP;
                            tempstr = mydevice.DeviceName;
                        }
                        hostsubnet = "255.0.0.0";
                        if (mydevice.DeviceName.ToLower().Contains("host"))
                        {
                            hostipaddr = mydevice.DeviceIP;
                        }
                    }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching cRIO Imaging Tool", tempstr, hostgateway);
                    ProcessStartInfo startInfo = new ProcessStartInfo();
	                startInfo.FileName = "C:\\Program Files (x86)\\National Instruments\\LabVIEW 2011\\project\\CRIO Tool\\FRC CRIO Imaging Tool.exe";
	                Process.Start(startInfo);                    
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to cRIO.  Check Connections");
                }
            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }
        }
        private void task_imagecrio_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Connect a Crossover Cable from this computer's LAN Connection to the cRIO Port 1.\r\n");
            t_Results.AppendText("Step 2:  Click this Link.  After a successful connection the cRIO Imaging Tool will be opened.");
        }
        private void task_imagecrio_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();
        }
        private void task_connectcamera2011_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            try
            {
                this.Cursor = Cursors.WaitCursor;
                string NIC = lb_NIC.SelectedItem.ToString();
                string tempstr = "";
                hostipaddr = "192.168.0.1";
                hostsubnet = "255.0.0.0";
                foreach (Device mydevice in myDevices)
                {
                    if (mydevice.DeviceName.ToLower().Contains("camera2011"))
                    {
                        hostgateway = mydevice.DeviceIP;
                        tempstr = mydevice.DeviceName;
                        break;
                    }
                }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching Web Browser", tempstr, hostgateway);
                    tempstr = "http:////" + hostgateway.ToString();
                    ProcessStartInfo sInfo = new ProcessStartInfo(tempstr);
                    Process.Start(sInfo);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to Camera.  Check Connections");
                }
                this.Cursor = Cursors.Default;

            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }
        }
        private void task_connectcamera2011_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Connect a Crossover Cable from this computer's LAN Connection to the Camera.\r\n");
            t_Results.AppendText("Step 2:  Power on the Camera and wait 30 seconds\r\n");
            t_Results.AppendText("Step 3:  Click this Link.  After a successful connection a Browser window will opened to the Camera.");
        }
        private void task_connectcamera2011_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();
        }

        private void task_connectcamera2012_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string tempstr = "";
                string NIC = lb_NIC.SelectedItem.ToString();
                foreach (NIC myNIC in myNICS)
                    foreach (Device mydevice in myDevices)
                    {
                        if (mydevice.DeviceName.ToLower().Contains("camera2012"))
                        {
                            hostgateway = mydevice.DeviceIP;
                            tempstr = mydevice.DeviceName;
                        }
                        hostsubnet = "255.0.0.0";
                        if (mydevice.DeviceName.ToLower().Contains("host"))
                        {
                            hostipaddr = mydevice.DeviceIP;
                        }
                    }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching Browser", tempstr, hostgateway);
                    tempstr = "http:////" + hostgateway.ToString();
                    ProcessStartInfo sInfo = new ProcessStartInfo(tempstr);
                    Process.Start(sInfo);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to Camera.  Check Connections");
                }
            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }
        }

        private void task_connectcamera2012_MouseHover(object sender, EventArgs e)
        {
            
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Bring the computer within range of the Robot and turn the Robot On or Connect with a LAN Connection.\r\n");
            t_Results.AppendText("Step 2:  Select the appropriate NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_connectcamera2012_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();

        }

        private void task_ConnectRadioFactory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
            
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string NIC = lb_NIC.SelectedItem.ToString();
                string tempstr = "";
                hostipaddr = "192.168.0.51";
                hostsubnet = "255.0.0.0";
                foreach (Device mydevice in myDevices)
                {
                    if (mydevice.DeviceName.ToLower().Contains("radiofactory"))
                    {
                        hostgateway = mydevice.DeviceIP;
                        tempstr = mydevice.DeviceName;
                        break;
                    }
                }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching Web Browser", tempstr, hostgateway);
                    tempstr = "http:////" + hostgateway.ToString();
                    ProcessStartInfo sInfo = new ProcessStartInfo(tempstr);
                    Process.Start(sInfo);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to Radio.  Check Connections");
                }
                this.Cursor = Cursors.Default;

            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }

        }

        private void task_ConnectRadioFactory_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Connect this computer's LAN Connection to a non-Internet port on the Radio.\r\n");
            t_Results.AppendText("Step 2:  Select the LAN NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_ConnectRadioFactory_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();

        }

        private void task_ConnectRadioConfigured_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string tempstr = "";
                string NIC = lb_NIC.SelectedItem.ToString();
                foreach (NIC myNIC in myNICS)
                    foreach (Device mydevice in myDevices)
                    {
                        if (mydevice.DeviceName.ToLower().Contains("router"))
                        {
                            hostgateway = mydevice.DeviceIP;
                            tempstr = mydevice.DeviceName;
                        }
                        hostsubnet = "255.0.0.0";
                        if (mydevice.DeviceName.ToLower().Contains("host"))
                        {
                            hostipaddr = mydevice.DeviceIP;
                        }
                    }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching Browser", tempstr, hostgateway);
                    tempstr = "http:////" + hostgateway.ToString();
                    ProcessStartInfo sInfo = new ProcessStartInfo(tempstr);
                    Process.Start(sInfo);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to Router.  Check Connections");
                }
            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }
        }

        private void task_ConnectRadioConfigured_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Bring the computer within range of the Robot and turn the Robot On or Connect with a LAN Connection.\r\n");
            t_Results.AppendText("Step 2:  Select the appropriate NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_ConnectRadioConfigured_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();

        }
        private void task_ConnectRobot_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string NIC = lb_NIC.SelectedItem.ToString();
                string tempstr = "";
                hostsubnet = "255.0.0.0";
                foreach (Device mydevice in myDevices)
                {
                    if (mydevice.DeviceName.ToLower().Contains("host"))
                    {
                        hostipaddr = mydevice.DeviceIP;
                    }
                    else if (mydevice.DeviceName.ToLower().Contains("crio"))
                    {
                        hostgateway = mydevice.DeviceIP;
                        tempstr = mydevice.DeviceName;
                        break;
                    }

                }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.", tempstr, hostgateway);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to cRIO.  Check Connections");
                }
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }

            
        }

        private void task_ConnectRobot_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Bring the computer within range of the Robot and turn the Robot On or Connect with a LAN Connection.\r\n");
            t_Results.AppendText("Step 2:  Select the appropriate NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_ConnectRobot_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();
            changeactivenic = true;
        }
        private void task_ConnectInternet_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string NIC = lb_NIC.SelectedItem.ToString();
                ChangeNetworkSettings_DHCP(NIC);
                UpdateCurrentIPSettings();
                if (pingdevice("www.google.com") > 0)
                {
                    t_Results.Text = string.Format("Connected to Internet Successfully.  Launching Web Browser");
                    ProcessStartInfo sInfo = new ProcessStartInfo("www.google.com");
                    Process.Start(sInfo);
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to the Internet.  Check Connections");
                }
                this.Cursor = Cursors.Default;

            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }

            
        }

        private void task_ConnectInternet_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Bring the computer within range of a configured Wifi Router or Connect with a LAN Connection.\r\n");
            t_Results.AppendText("Step 2:  Select the appropriate NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_ConnectInternet_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();
            changeactivenic = true;

        }
        private void task_ftpcrio_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string tempstr = "";
                string NIC = lb_NIC.SelectedItem.ToString();
                foreach (NIC myNIC in myNICS)
                    foreach (Device mydevice in myDevices)
                    {
                        if (mydevice.DeviceName.ToLower().Contains("crio"))
                        {
                            hostgateway = mydevice.DeviceIP;
                            tempstr = mydevice.DeviceName;
                        }
                        hostsubnet = "255.0.0.0";
                        if (mydevice.DeviceName.ToLower().Contains("host"))
                        {
                            hostipaddr = mydevice.DeviceIP;
                        }
                    }
                ChangeNetworkSettings_STATIC(NIC, hostipaddr, hostsubnet, hostgateway);
                UpdateCurrentIPSettings();
                if (pingdevice(hostgateway) > 0)
                {
                    t_Results.Text = string.Format("Connected to: {0}({1}) Successfully.  Launching FTP Client", tempstr, hostgateway);
                    //Open FTP Client to cRIO
                }
                else
                {
                    t_Results.Text = string.Format("Error Connecting to cRIO.  Check Connections");
                }
            }
            catch (Exception ex)
            {
                t_Results.Clear();
                t_Results.AppendText(ex.Message);
                this.Cursor = Cursors.Default;
            }
        }

        private void task_ftpcrio_MouseHover(object sender, EventArgs e)
        {
            t_Results.Clear();
            t_Results.AppendText("Step 1:  Bring the computer within range of the Robot and turn the Robot On or Connect with a LAN Connection.\r\n");
            t_Results.AppendText("Step 2:  Select the appropriate NIC.\r\n");
            t_Results.AppendText("Step 3:  Click this Link.");
        }

        private void task_ftpcrio_MouseLeave(object sender, EventArgs e)
        {
            t_Results.Clear();
        }
        #endregion


        

        

        

       






    }
}
